package RegisterServlet;


import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.dbutils.QueryRunner;
import cn.jhc.Global;
import cn.jhc.bean.User;
import cn.jhc.db.UserDao;

@WebServlet("/uploadMulti.do")
@MultipartConfig(maxRequestSize=10485760)
public class MultiPartRegisterServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		String vcode = getContent(req.getPart("vcode"));
		String expected = (String) req.getSession().getAttribute(Global.VCODE_KEY);
		if(!vcode.equals(expected)) {
			resp.sendRedirect("./register.jsp");
			return;
		}
		
		String contextPath = req.getServletContext().getRealPath("/upload");
		File uploadDir = new File(contextPath);
		if(!uploadDir.exists()) {
			uploadDir.mkdirs();
		}
		
//		System.out.println(contextPath);
		Part filePart = req.getPart("file");
		String filename = filePart.getSubmittedFileName();
		String extName = filename.substring(filename.lastIndexOf("."));
		if(!extName.equalsIgnoreCase(".jpg") && !extName.equalsIgnoreCase(".png")) {
			throw new ServletException("Not supported image type.");
		}
		String diskFilename = System.currentTimeMillis() + extName;
		String diskFile = contextPath + File.separator + diskFilename;
		filePart.write(diskFile);
	
		Map<String, String> map = new HashMap<>();
		for(Part part : req.getParts()) {
			if(part.getName().equals("file")) 
				continue;
			String content = getContent(part);
			String key = part.getName();
			if(map.get(key) == null) {
				map.put(key, content);
			} else {
				String newValue = map.get(key) + "," + content;
				map.put(key, newValue);
			}
		}
		
		QueryRunner runner = (QueryRunner) req.getServletContext().getAttribute("runner");
		User user = new User(map.get("username"), map.get("pwd"), diskFilename, map.get("sex"), map.get("interests"));
		try {
			UserDao.register(runner, user);
		} catch (SQLException e) {
			e.printStackTrace();
			resp.sendError(500);
			return;
		}
		
		resp.sendRedirect("./upload/" + diskFilename);
	}
	
	private String getContent(Part part) throws IOException {
		try(Scanner scanner = new Scanner(part.getInputStream())) {
			return scanner.next();
		}
	}
}